const Logger = require('../Logger');

process
	.on('uncaughtException', function handleError(error) {
		Logger.log(error);
	})
	.on('unhandledRejection', function handleRejection(error) {
		Logger.log(error);
	});


class Task {
	constructor(ModelManager, Browser) {
		this.active = true;

		this.Model = ModelManager.Model.ErrorModel;
		this.Browser = Browser;
		this.Logger = Logger;
		this.sequelize = ModelManager.sequelize;
	}

	async save() {
		const sequelize = this.sequelize;

		return new Promise(resolve => {
			(async function loopSync(self) {
				const transaction = await sequelize.transaction();

				const data = await self.Model.findOne({
					lock: true,
					skipLocked: true,
					where: {
						status: 0
					},
					order: [
						['uploadTime', 'ASC']
					]
				});

				if (!data) {
					console.log('未找到符合要求的数据, 所有数据处理完成');
					self.end();
					process.exit(0);
				}

				data.status = 1;

				await data.save({ transaction });
				console.log('当前处理模型:' + data.modelId);

				try {
					// 执行数据保存逻辑
					await self.Browser.saveData(data);

					// 保存成功， 修改数据状态
					data.status = 3;
					data.updateAt = Date.now();

					const t = `模型:${data.modelId} 保存成功 \n`;

					console.log(t);
					self.Logger.log(t);
					await data.save({ transaction });
					await transaction.commit();
				} catch (error) {
					data.status = 2;
					data.updateAt = Date.now();
					data.errorDetail = error.message;

					const t = `模型:${data.modelId} 保存失败 \n`;

					console.log(t);
					self.Logger.log(t);

					await data.save({ transaction });
					await transaction.commit();
					await self.Browser.close();

					self.Browser = null;
				}

				resolve();
			})(this);
		});
	}

	async start() {
		try {
			this.active = true;

			await this.Browser.launch();
			this.Logger.log('浏览器启动成功 \n');

			await this.Browser.login();
			this.Logger.log('登录成功 \n');

			await this.Browser.gotoOrderPage();
		} catch (error) {
			console.log('启动浏览器失败');

			process.exit(1);
		}

		(async function loop(self) {
			if (self.active) {
				if (!self.Browser) {
					process.exit(1);
				}
				else {
					await self.save();

					setTimeout(() => loop(self), 3000);
				}
			}
		})(this);
	}

	end() {
		this.active = false;
		this.Browser.close();
	}
}

exports.Task = Task;